<template>
  <div>
    <el-form
      :disabled="!canEdit"
      :model="ruleForm"
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item label="标题" prop="title">
        <el-input style="width: 50%" v-model="ruleForm.title"></el-input>
      </el-form-item>

      <el-form-item label="图片">
        <!-- :class="{ hide: hideUpload }" 
        :limit="3" -->
        <el-upload
          action="test"
          list-type="picture-card"
          :on-remove="handleRemoveImage"
          :file-list="ruleForm.images"
          :http-request="uploadImage"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="视频">
        <el-upload
          accept=".mp4"
          style="width: 50%"
          action="test"
          :on-remove="handleRemoveVideo"
          :limit="1"
          :file-list="ruleForm.video"
          :before-upload="beforeVideoUpload"
          :http-request="uploadVideo"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <video
          style="width: 146px; height: 146px"
          controls
          v-if="ruleForm.video && ruleForm.video[0]"
          :src="ruleForm.video[0].url"
        ></video>
      </el-form-item>

      <el-form-item label="昵称" prop="pet_nickname">
        <el-input style="width: 50%" v-model="ruleForm.pet_nickname"></el-input>
      </el-form-item>

      <el-form-item label="年龄" prop="pet_age">
        <el-select v-model="ruleForm.pet_age" placeholder="请选择年龄">
          <el-option
            v-for="item in dict.pet_age"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="分类" prop="category_id">
        <el-select v-model="ruleForm.category_id" placeholder="请选择分类">
          <el-option
            v-for="item in dict.pet_type"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="性别" prop="pet_sex">
        <el-select v-model="ruleForm.pet_sex" placeholder="请选择性别">
          <el-option
            v-for="item in dict.pet_sex"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="丢失时间" prop="lost_time">
        <el-date-picker
          v-model="ruleForm.lost_time"
          type="datetime"
          value-format="yyyy-MM-dd hh:mm"
          format="yyyy-MM-dd hh:mm"
          placeholder="请选择丢失时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="丢失地点" prop="location">
        <el-input
          disabled
          style="width: 50%"
          v-model="ruleForm.location"
        ></el-input>
        <el-button type="success" @click="showMapModal = true"
          >选择地址</el-button
        >
      </el-form-item>

      <el-form-item label="丢失详情" prop="detail">
        <el-input
          type="textarea"
          rows="5"
          style="width: 50%"
          v-model="ruleForm.detail"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="action">
      <el-button v-if="canEdit" type="primary" @click="submitForm"
        >立即保存</el-button
      >
      <el-button v-else type="primary" @click="canEdit = true"
        >重新编辑</el-button
      >
    </div>

    <Map
      v-model="showMapModal"
      @ok="chooseAddress"
      :address="ruleForm.location"
    ></Map>
  </div>
</template>

<script>
import { getCommonDataDict, uploadFile } from "@/api/common";
import { getInfo, update } from "@/api/find_pets";
import Map from "@/components/Map";

export default {
  props: ["id"],
  components: {
    Map,
  },
  data() {
    return {
      canEdit: false,
      ruleForm: {},
      dict: {},
      showMapModal: false,
      hideUpload: false,
    };
  },
  mounted() {
    this.getBaseData();
    this.getInfo();
  },
  methods: {
    async getBaseData() {
      const res = await getCommonDataDict();

      let dict = res.data;
      Object.entries(dict).forEach((item) => {
        const field = item[0];
        const obj = item[1];
        let objArr = [];
        if (field != "pet_age") {
          Object.entries(obj).forEach((sub) => {
            const id = sub[0] * 1;
            const name = sub[1];
            objArr.push({
              id,
              name,
            });
          });
        } else {
          objArr = obj;
        }
        dict[field] = objArr;
      });

      this.dict = dict;
    },
    async getInfo() {
      const res = await getInfo({ id: this.id });
      if (res.data) {
        const obj = res.data;
        obj.images = obj.images.map((item) => {
          item.url = item.attachment;
          return item;
        });
        this.hideUpload = obj.images.length === 3;

        if (obj.video) {
          obj.video = [obj.video].map((item) => {
            item.url = item.attachment;
            item.name = item.filename;
            return item;
          });
        } else {
          obj.video = [];
        }
        this.ruleForm = obj;
      }
    },
    async uploadImage({ file }) {
      const formdata = new FormData();
      formdata.append("file", file);
      formdata.append("dir", "find_pet");
      formdata.append("filetype", "image");

      const res = await uploadFile(formdata);
      this.ruleForm.images.push({
        id: 0,
        attachment: res.data.filename,
        status: "success",
        name: res.data.filename,
        url: res.data.filepath,
      });
      this.hideUpload = this.ruleForm.images.length >= 3;
    },
    handleRemoveImage(file, fileList) {
      this.ruleForm.images = fileList;
      this.hideUpload = fileList >= 3;
    },
    handleRemoveVideo(file, fileList) {
      this.ruleForm.video = fileList;
    },
    beforeVideoUpload(file) {
      const isMp4 = file.type === "video/mp4";
      if (!isMp4) {
        this.$message.error("请上传mp4格式的视频");
      }
      return isMp4;
    },
    async uploadVideo({ file }) {
      const formdata = new FormData();
      formdata.append("file", file);
      formdata.append("dir", "find_pet");
      formdata.append("filetype", "video");

      const loading = this.$loading({
        lock: true,
        text: "视频上传中，请耐心等待。",
      });

      const res = await uploadFile(formdata);
      loading.close();

      this.ruleForm.video = [
        {
          id: 0,
          attachment: res.data.filename,
          status: "success",
          name: res.data.filename,
          url: res.data.filepath,
        },
      ];
    },

    async submitForm() {
      const postData = Object.assign({}, this.ruleForm);
      if (postData.video) {
        postData.video = postData.video[0];
      }
      const res = await update(postData);
      if (res) {
        this.$message({
          message: res.msg,
          type: "success",
        });
        this.$router.go(-1);
      }
    },
    chooseAddress(location) {
      this.ruleForm.lat = location.lat;
      this.ruleForm.lng = location.lng;
      this.ruleForm.location = location.address;
    },
  },
};
</script>
<style lang="scss">
.action {
  padding-left: 100px;
}
.hide {
  .el-upload--picture-card {
    display: none;
  }
}
</style>